<?php
/**
 * Zeus_DataGrid
 *
 * @package
 * @author xexplorer
 * @copyright Copyright (c) 2008
 * @version $Id$
 * @access public
 */
class zeus_datagrid {
    private $sAction;
    private $sMatch;
    private $sFilter;
    private $sFilterField;
    private $bWholeOnly;
    private $sOrder;
    private $sOrderType;
    private $aColumn;
    private $aField;
    private $sTable;
    private $sGridTitle;
    private $aSubMenu;
    private $iShowRecord;
    private $iRecordCount;
    private $iPageRange;
    private $iPageNo;
    private $iPageCount;
    private $iStart;
    private $aOrderName;
    private $aOrderType;
    private $oForm;
    private $sIdColumn;
    private $aSelect;
    private $bDelete;
    private $bView;
    private $bEdit;
    private $bAdd;
    private $bDebug;
    /**
     * Constructor
     *
     * @access protected
     */
    public function __construct()
    {
        $this->iStart = isset($_GET['start'])?$_GET['start']:0;
        $this->iShowRecord = isset($_POST['display'])?$_POST['display']:15;
        $this->aCheckId = array();
        $this->bEdit = false;
        $this->bAdd = false;
        $this->bView = false;
        $this->bDelete = false;
        $this->bDebug = false;
    }
    public function __destruct()
    {
    }
    /**
     * Zeus_DataGrid::__set()
     *
     * @param mixed $name
     * @param mixed $value
     * @return
     */
    public function __set($name, $value)
    {
        $this->$name = $value;
    }
    /**
     * Zeus_DataGrid::__get()
     *
     * @param mixed $name
     * @return
     */
    public function __get($name)
    {
        return $this->$name;
    }
    /**
     * Zeus_DataGrid::select()
     *
     * @return
     */
    public function select()
    {
        // Build query string
        $table = implode(",", $this->sTable);
        $field = implode(",", $this->aField);
        $match = (isset($this->sMatch))?(implode(" AND ", $this->sMatch)):null;
        $filter = $this->toSqlString($this->sFilter);
        $filterField = $this->toSqlString($this->sFilterField);
        $order = $this->toSqlString($this->sOrder);
        $orderType = strtoupper($this->toSqlString($this->sOrderType));
        $start = $this->toSqlString($this->iStart);
        $display = $this->toSqlString($this->iShowRecord);

        if (!$this->bWholeOnly && isset($this->bWholeOnly) && '' != $this->sFilter) {
            $filter = "%" . $filter . "%";
        }
        $sql = "SELECT " . $field . " FROM " . $table;
        if (isset($match)) {
            $sql .= " WHERE " . $match;
            if (isset($filter) && "" != $filter && isset($filterField) && "" != $filterField) {
                $sql .= " AND " . $filterField . " LIKE '" . $filter . "'";
            } elseif (isset($filter) && "" != $filter) {
                foreach($this->aField as $field) {
                    $filterString[] = "(" . $field . " LIKE '" . $filter . "')";
                }
                $sql .= " AND (" . implode(" OR ", $filterString) . ")";
            } else {
                $sql .= "";
            }
        } else {
            if (isset($filter) && "" != $filter && isset($filterField) && "" != $filterField) {
                $sql .= " WHERE " . $filterField . " LIKE '" . $filter . "'";
            } elseif (isset($filter) && "" != $filter) {
                foreach($this->aField as $field) {
                    $filterString[] = "(" . $field . " LIKE '" . $filter . "')";
                }
                $sql .= " WHERE " . "(" . implode(" OR ", $filterString) . ")";
            } else {
                $sql .= "";
            }
        }
        if (isset($_GET['order']) && "" != $order && null != $order) {
            $sql .= " ORDER BY " . $order;
        }
        if (isset($_GET['type']) && "" != $orderType) {
            $sql .= " " . $orderType;
        }
        if (isset($display) && "" != $display) {
            $limit = " LIMIT " . $display;
            if (isset($start) && "" != $start) {
                $limit = " LIMIT " . $start . "," . $display;
            }
            $sql .= $limit;
        }
        // run query
        $result = zeus_sql_query($sql, $this->bDebug, 'All');
        return $result;
    }
    /**
     * Zeus_DataGrid::getRecordCount()
     *
     * @return
     */
    public function getRecordCount()
    {
        $table = implode(",", $this->sTable);
        $match = (isset($this->sMatch))?(implode(" AND ", $this->sMatch)):null;
        $filter = $this->toSqlString($this->sFilter);
        $filterField = $this->toSqlString($this->sFilterField);
        if (!$this->bWholeOnly && isset($this->bWholeOnly) && '' != $this->sFilter) {
            $filter = "%" . $filter . "%";
        }
        $sql = "SELECT COUNT(DISTINCT $this->sIdColumn) FROM " . $table;
        if (isset($match)) {
            $sql .= " WHERE " . $match;
            if (isset($filter) && "" != $filter && isset($filterField) && "" != $filterField) {
                $sql .= " AND " . $filterField . " LIKE '" . $filter . "'";
            } elseif (isset($filter) && "" != $filter) {
                foreach($this->aField as $field) {
                    $filterString[] = "(" . $field . " LIKE '" . $filter . "')";
                }
                $sql .= " AND (" . implode(" OR ", $filterString) . ")";
            } else {
                $sql .= "";
            }
        } else {
            if (isset($filter) && "" != $filter && isset($filterField) && "" != $filterField) {
                $sql .= " WHERE " . $filterField . " LIKE '" . $filter . "'";
            } elseif (isset($filter) && "" != $filter) {
                foreach($this->aField as $field) {
                    $filterString[] = "(" . $field . " LIKE '" . $filter . "')";
                }
                $sql .= " WHERE " . "(" . implode(" OR ", $filterString) . ")";
            } else {
                $sql .= "";
            }
        }
        // run query
        $result = zeus_sql_query($sql, $this->bDebug);
        return $result["COUNT(DISTINCT $this->sIdColumn)"];
    }
    /**
     * Zeus_DataGrid::showSubMenu()
     *
     * @param string $target
     * @return
     */
    public function showSubMenu()
    {
        $subMenu = $this->aSubMenu;
        if (is_array($subMenu)) {
            foreach($subMenu as $sub_key => $sub_value) {
                if ($value == $_GET['status']) {
                    $class = "class='current'";
                } else {
                    $class = "";
                }
                if (null == $sub_value) {
                    $menu[] = "<a href='" . $_SERVER['PHP_SELF'] . "'>" . $sub_key . "</a></li>";
                } else {
                    $menu[] = "<a href='" . $_SERVER['PHP_SELF'] . "?status="
                     . $sub_value . "'>" . $sub_key . "</a></li>";
                }
            }
            $menuToShow = implode(" |", $menu);
        } else {
            zeus_do_nothing();
        }
        return $menuToShow;
    }
    /**
     * Zeus_DataGrid::showSelect()
     *
     * @return
     */
    public function showSelect()
    {
        if (isset($this->aSelect) && is_array($this->aSelect)) {
            if ($this->bDelete) {
                $selectToShow = $this->oForm->addElement("submit", array("value" => _e("Delete"), "name" => "deleteit", "class" => "button-secondary delete"));
            } else {
                $selectToShow = "";
            }
            foreach($this->aSelect AS $select) {
                $selectToShow .= $this->oForm->addSelect($select['property'], $select['options'],$select['current']);
            }
            $selectToShow .= $this->oForm->addElement("submit", array("value" => _e("Filtrate"), "name" => "filtrate", "class" => "button-secondary delete"));
        } else {
            $selectToShow = $this->oForm->addElement("submit", array("value" => _e("Delete"), "name" => "deleteit", "class" => "button-secondary delete"));
        }
        return $selectToShow;
    }
    /**
     * Zeus_DataGrid::showSearch()
     *
     * @return
     */
    public function showSearch()
    {
        $searchToShow = $this->oForm->addElement("text", array("id" => "post-search-input", "name" => "search", "value" => $_GET['search']));
        $searchToShow .= $this->oForm->addElement("submit", array("name" => "submit", "value" => _e('Search'), "class" => "button"));
        return $searchToShow;
    }
    /**
     * Zeus_DataGrid::showColumnTitle()
     *
     * @return
     */
    public function showColumn()
    {
        unset($_GET['start']);
        $column = "\n\t<tr>";
        $type = $this->setOrderType();
        foreach($this->aColumn AS $column_key => $column_value) {
            if ('checkbox' === $column_key) {
                $class = ' class="check-column"';
            } elseif ('comments' === $column_key) {
                $class = ' class="num"';
            } else {
                $class = '';
            }
            $column .= "\n\t<th scope='col' " . $class . ">"
             . "<a href='" . $_SERVER['PHP_SELF'] . "?"
             . $this->toGetUrl(array(array("order" => $column_value['field']),
                    array("type" => $type)))
             . "'>" . $column_value['name'] . "</a></th>";
        }
        $column .= "\n\t</tr>";
        return $column;
    }
    /**
     * Zeus_DataGrid::setOrderType()
     *
     * @return
     */
    private function setOrderType()
    {
        $type = ("desc" == $_GET['type'])?"asc":"desc";
        return $type;
    }
    /**
     * Zeus_DataGrid::showPageNav()
     *
     * @return
     */
    public function showPageNav()
    {
        $start = 0;
        $endSize = 1;
        $midSize = 2;
        $dots = false;
        $this->iRecordCount = $this->getRecordCount();
        $this->iPageCount = ceil($this->iRecordCount / $this->iShowRecord);
        $this->iPageNo = ($this->iStart / $this->iShowRecord) + 1;
        if ($this->iRecordCount < 2) {
            return false;
        }
        if (($this->iStart) >= ($this->iShowRecord)) {
            $prev = ($this->iStart) - ($this->iShowRecord);
            $prevUrl = $_SERVER['PHP_SELF'] . "?" . $this->toGetUrl(array(array("start" => $prev)));
            $prevText = _e('&laquo; Previous');
            $pageLink[] = "<a class='prev page-numbers' href='" . $prevUrl . "'>" . $prevText . "</a>";
        }
        if (isset($this->iPageCount)) {
            for($rsNo = 1;$rsNo <= $this->iPageCount;$rsNo++) {
                if ($rsNo == $this->iPageNo) {
                    $pageLink[] = "<span class='page-numbers current'>" . $rsNo . "</span>";
                    $dots = true;
                } elseif ($rsNo <= $endSize || ($this->iPageNo && $rsNo >= $this->iPageNo - $midSize && $rsNo <= $this->iPageNo + $midSize) || $rsNo > $this->iPageCount - $endSize) {
                    $pageLink[] = "<a class='page-numbers' href='" . $_SERVER['PHP_SELF'] . "?" . $this->toGetUrl(array(array("start" => $start))) . "'>" . $rsNo . "</a>";
                    $dots = true;
                } elseif ($dots = true) {
                    $pageLink[] = "<span class='page-numbers dots'>...</span>";
                    if ($this->iPageNo < 2 * $midSize + $endSize || $rsNo < $this->iPageCount - $endSize) {
                        $pageLink = array_unique($pageLink);
                    }
                    $dots = false;
                } else {
                    zeus_do_nothing();
                }
                $start += $this->iShowRecord;
            }
        }
        if ((($this->iStart) + ($this->iShowRecord)) < ($this->iRecordCount)) {
            $next = ($this->iStart) + ($this->iShowRecord);
            $nextUrl = $_SERVER['PHP_SELF'] . "?" . $this->toGetUrl(array(array("start" => $next))) ;
            $nextText = _e('Next &raquo;');
            $pageLink[] = "<a class='next page-numbers' href='" . $nextUrl . "'>" . $nextText . "</a>";
        }
        if (null != $pageLink) {
            $nav = implode("\n", $pageLink);
            return $nav;
        } else {
            return false;
        }
    }
    /**
     * Zeus_DataGrid::toGetUrl()
     *
     * @return
     */
    private function toGetUrl($aNewGet = array())
    {
        $url = null;
        if (isset($aNewGet)) {
            foreach($aNewGet As $new) {
                if (null != array_values($new)) {
                    $_GET = array_merge($_GET, $new);
                } else {
                    zeus_do_nothing();
                }
            }
        }
        if (isset($_GET)) {
            foreach($_GET AS $get_key => $get_value) {
                $getUrl[] = $get_key . "=" . $get_value;
            }
            ksort($getUrl);
            $url = implode("&", $getUrl);
        }
        return $url;
    }
    /**
     * Zeus_DataGrid::toSqlString()
     *
     * @param mixed $string
     * @return
     */
    private function toSqlString($sSql = "")
    {
        return str_replace("'", "''", $sSql);
    }
}

?>